package com.gz.eventprocess;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class ballmove extends JFrame {
    Mypanel mypanel=null;
    public static void main(String[] args) {
        new ballmove();
    }

    public ballmove() {
        mypanel=new Mypanel();
        this.add(mypanel);
        this.setSize(400,300);
        this.addKeyListener(mypanel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

    }
}

class Mypanel extends JPanel implements KeyListener{//keylistenr监听器

    int x=10;
    int y=10;

    public void paint(Graphics g) {
        super.paint(g);
        //每次重置x,y重绘圆形，实现移动
        g.fillOval(x,y,20,20);

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {//

//        System.out.println((char) e.getKeyCode()+"被按下");
        if(e.getKeyCode()==KeyEvent.VK_LEFT){
            x--;
        }
        else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
            x++;
        }
        else if(e.getKeyCode()==KeyEvent.VK_UP){
            y--;
        }
        else if(e.getKeyCode()==KeyEvent.VK_DOWN){
            y++;
        }
        this.repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}